import requests  # type: ignore
import json
from datetime import datetime, timedelta
import logging
from urllib.parse import urljoin  # 添加导入

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("DailyInspection")

class PrometheusClient:
    def __init__(self, url, headers=None):
        # 确保URL格式正确，移除末尾的斜杠
        self.base_url = url.rstrip("/")
        self.headers = headers or {}
        
    def query_range(self, query, hours=24):
        """执行范围查询"""
        end_time = datetime.now()
        start_time = end_time - timedelta(hours=hours)
        
        params = {
            "query": query,
            "start": start_time.timestamp(),
            "end": end_time.timestamp(),
            "step": "5m"  # 5分钟粒度
        }
        
        try:
            # 使用 urljoin 来正确构建URL
            url = urljoin(self.base_url + "/", "api/v1/query_range")
            response = requests.get(
                url,
                params=params,
                headers=self.headers,
                timeout=10
            )
            response.raise_for_status()  # 检查HTTP错误
            return response.json()
        except Exception as e:
            logger.error(f"Prometheus查询失败: {e}")
            return None

class InspectionAgent:
    def __init__(self, prometheus_url):
        self.prom_client = PrometheusClient(prometheus_url)
        self.queries = {
            "node_cpu": '100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100)',
            "node_memory": '100 * (1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)',
            "node_disk": '100 - node_filesystem_free_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} * 100',
            "jvm_memory": '100 * (1 - jvm_memory_used_bytes{area="heap"} / jvm_memory_max_bytes{area="heap"})',
            "app_healthcheck": 'site_up{job="services-status-exporter"}',
            "site_xunjian": 'probe_success{job="blackbox_http_200"}',
            "disk_io": 'rate(node_disk_io_time_seconds_total[5m])',
            # 添加中间件相关的查询
            "mysql_up": 'mysql_up',
            "redis_up": 'redis_up',
            "rabbitmq_up": 'rabbitmq_build_info'
        }
        
    def collect_metrics(self):
        """采集核心指标"""
        results = {}
        for key, query in self.queries.items():
            # 将查询时间范围改为12小时
            data = self.prom_client.query_range(query, hours=12)
            if data:
                results[key] = {
                    "query": query,
                    "data": data,
                    "timestamp": datetime.now().isoformat()
                }
            else:
                logger.warning(f"查询 {key} 返回空数据")
        return results
